package com.zj.musicTools.page

import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.zj.musicTools.MainActivity.Companion.Agent
import com.zj.musicTools.MainActivity.Companion.CONTEXT
import com.zj.musicTools.R
import com.zj.musicTools.function.AppPath.Companion.appPath
import com.zj.musicTools.function.SQLwriter.Companion.configData
import com.zj.musicTools.ui.theme.MusicToolsTheme
import java.io.File

/**
 * 下拉列表组合包装
 * list：下拉列表的list
 * titleText：下拉列表的说明
 * switched：切换列表项后的生效函数
 * moreLayout:给列表行组件增加组件
* */
@Composable
fun DownList(list:List<String>, titleText:String, moreLayout: @Composable (Int)->Unit={}, switched:(Int)->Unit){
    var expander by remember { mutableStateOf(false) }
    var indexList by remember { mutableStateOf(0) }

    Row(
        Modifier
            .width(330.dp)
            .height(60.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween){
        Text(text = titleText,
            Modifier
                .align(Alignment.CenterVertically)
                .align(Alignment.Top)
                .padding(3.dp))
        var menuWidth by remember { mutableStateOf(30) }

        Row {
            Box(
                Modifier
    //                    .width(menuWidth.dp)
                    .padding(8.dp)
                    .border(
                        1.dp,
                        color = MaterialTheme.colorScheme.primary,
                        shape = RoundedCornerShape(5.dp)
                    )
            ) {
                Text(
                    text = list[indexList],
                    modifier = Modifier
                        .clickable(enabled = buttonState.clickable) { expander = !expander }
                        .align(Alignment.Center)
                        .padding(10.dp)
                        .onGloballyPositioned { coordinates ->
                            // 获取控件的宽度
                            menuWidth = coordinates.size.width
                        },
                )
                DropdownMenu(
                    expanded = expander,
                    onDismissRequest = { expander = false },
                    modifier = Modifier.width(menuWidth.dp)
                ) {
                    list.forEachIndexed { index, s ->
                        DropdownMenuItem(
                            onClick = {
                                indexList = index
                                expander = false
                                switched(index)
                            },
                            text = { Text(text = s) }
                        )
                    }
                }


            }
            moreLayout(indexList)

        }
    }
}

fun save(){


}

/**
 * 快速清理指定路径的指定类型文件
 * */
fun clearQuick(directoryPath: String, suffix: String){
        val directory = File(directoryPath)
        if (directory.exists() && directory.isDirectory) {
            directory.listFiles()?.forEach { file ->
                if (file.isFile && file.name.endsWith(suffix)) {
                    file.delete()
                }
            }
        } else {
            Log.e("clearQuick()","Directory does not exist or is not a directory: $directoryPath")
            Agent.newLog("<Err>Directory does not exist or is not a directory: $directoryPath")
        }

}


@Composable
fun setPage() {
    var selectedPath:String? by remember { mutableStateOf("") }
    var savePath by remember { mutableStateOf("/sdcard/Download/netease/cloudmusic/Music/") }//常用路径
    var clearPath by remember { mutableStateOf(appPath.output?:"") }//默认等于输出目录 Mark: 因为路径获取还未写完，所以暂时不用

    val inputPathType = listOf("自定义","上次使用","网易云","酷狗","QQ音乐","酷我")
    val outputPathType = listOf("原路径","自定义","上次使用","网易云","酷狗","QQ音乐","酷我")
    val outFileType = listOf("flac","mp3","wav","m4a","rm","aiff","aif","au","caf","dts","spdif")
    val clearType = listOf("flac","mp3","wav","m4a","rm","aiff","aif","au","caf","dts","spdif")
    val outNameType = listOf("原名","自定义")
    var outName by remember { mutableStateOf("") }

    var inputPathIndex by remember { mutableStateOf(0) }
    var outputPathIndex by remember { mutableStateOf(0) }
    var outTypeIndex by remember { mutableStateOf(0) }
    var outNameIndex by remember { mutableStateOf(0) }
    var clearTypeIndex by remember { mutableStateOf(0) }

    val focusManager = LocalFocusManager.current

    val dirLauncher=rememberLauncherForActivityResult(
        contract =  ActivityResultContracts.OpenDocumentTree() ,
        onResult = {
            runResult=""
            it?.let {
                selectedPath = appPath.UriToPath(CONTEXT,it)//Mark: 无法获取路径
                Log.i("Launcher PathSelect()", selectedPath.toString())
//                appPath.updateInputPath(it)//更新PATH类路径
            }
        })

    Column(modifier = Modifier
        .fillMaxSize()
        .padding(bottom = 60.dp).pointerInput(Unit){
           detectTapGestures {
                focusManager.clearFocus()
           }
        },
        verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally
    )
    {
//        Text(text = "敬请期待")
        OutlinedTextField(
            label = { Text("自定义：", color = colorResource(R.color.black),
                style = TextStyle(fontWeight = FontWeight.Bold)
            )
                    },
            modifier = Modifier
                .width(330.dp)
                .padding(2.dp),
            colors = TextFieldDefaults.colors(
                focusedTextColor = Color.Black,
                focusedContainerColor = Color.White,
                unfocusedContainerColor = Color.White,
                disabledContainerColor = Color.White,
                unfocusedIndicatorColor = MaterialTheme.colorScheme.primary
            ),

            value = savePath,
            textStyle = TextStyle(
                fontSize = 13.sp,
                fontWeight = FontWeight.Bold
            ),
            onValueChange = {
//                    newText->
//                savePath = newText
                Log.i("TextField()","input change value: ${it}")
            },keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text, imeAction = ImeAction.Done),
            keyboardActions = KeyboardActions(onDone = {
//                Log.i("input Done!!!","put msg:${startTime}")
                focusManager.clearFocus()
            }),
            trailingIcon={
                IconButton(
                    onClick = {
                        selectedPath = savePath
                        dirLauncher.launch(null)
                        savePath = selectedPath?:"" //Mark: 应该无法生效，想想其他方法（用一个变量来确定选择更新哪一个值就可以解决）
                        configData.set("CustomPath",savePath)

                    }, colors = IconButtonDefaults.iconButtonColors(
                    contentColor = MaterialTheme.colorScheme.primary)
                ) {
                    Icon(painter = painterResource(id = R.drawable.ic_dir_icon), contentDescription = "选择路径")
                }
            }
        )
        DownList(inputPathType,"默认输入路径：") {
//            inputPathIndex = it
            configData.set("DefInputPath",inputPathType[it])
        }
        DownList(outputPathType,"默认输出路径：") {
//            outputPathIndex = it
            configData.set("DefOutputPath",outputPathType[it])

        }
        DownList(outNameType,"输出文件名：", moreLayout = {index ->
            if(index == 0)Text(text = "+ ",Modifier.align(Alignment.CenterHorizontally))
            OutlinedTextField(value = outName, onValueChange = {
                outName = it
                configData.set("OutputFileName",outName)
            },modifier = Modifier
                .width(90.dp).height(60.dp)
                .padding(2.dp).align(Alignment.CenterHorizontally),
                colors = TextFieldDefaults.colors(
                    focusedTextColor = Color.Black,
                    focusedContainerColor = Color.White,
                    unfocusedContainerColor = Color.White,
                    disabledContainerColor = Color.White,
                    unfocusedIndicatorColor = MaterialTheme.colorScheme.primary
                ),textStyle = TextStyle(
                    fontSize = 13.sp,
                    fontWeight = FontWeight.Bold
                )
                ,keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text, imeAction = ImeAction.Done),
                keyboardActions = KeyboardActions(onDone = {
                    focusManager.clearFocus()
                }))
        }) {


            configData.set("OutputFileNameType",outNameType[it])
        }

        DownList(outFileType,"输出文件类型：") {
            configData.set("OutputFileType",outFileType[it])
        }


        Text(text = "清理路径：",
            Modifier
                .width(330.dp)
                .align(Alignment.CenterHorizontally)
                .padding(3.dp))


        Text(
            modifier = Modifier
                .width(320.dp)
                .border(
                    1.dp,
                    color = MaterialTheme.colorScheme.primary,
                    shape = RoundedCornerShape(5.dp)
                )
                .padding(16.dp)
                .clickable {
                    Log.i("!!!!!!!!!", "Text had clicked!")
                    dirLauncher.launch(null)
                    clearPath=selectedPath.toString()
                },
            text = clearPath,
            style = TextStyle(
                fontSize = 14.sp,
                color = colorResource(id = R.color.black),
                fontWeight = FontWeight.Bold
            )
        )
        DownList(clearType,"一键清理文件类型：") {
            clearTypeIndex=it
        }

        Button(onClick = {
            clearQuick(clearPath,clearType[clearTypeIndex])

        }) {
            Text("一键清理目录")
        }
    }

}

@Preview(showBackground = true )
@Composable
private fun DefaultPreview() {
    MusicToolsTheme {
        setPage()
    }
}

/**
 * 一键保存软件目录
 * 一键清除指定后缀文件
 *
 * 将设置数据保存到本地，包括默认模式、默认输入目录，默认输出目录，默认输出文件名样式（原名改类型/原名加后缀并改类型）,是否自动解密
 *
 * 数据类完成，可以根据需求来设计需要存储的数据了
 *
 * */